package com.tcheung.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * IOUtil
 *
 * @author: zhangteng
 * @time: 2014/11/29 18:29
 */
public class IOUtil {

    // classpath前缀
    public static final String CLASSPATH = "classpath:";

    public static InputStream getFileAsStream(String path) {
        if (path.startsWith(CLASSPATH)) {
            path = path.substring(CLASSPATH.length());
            return getClassLoader().getResourceAsStream(path);
        } else {
            try {
                return new FileInputStream(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static ClassLoader getClassLoader() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = IOUtil.getClassLoader();
        }
        return classLoader;
    }
}
